<template>
  <div class="food-detail-view">
    <div class="container">
      <div class="food-detail-card">
        <div class="food-images">
          <img :src="currentMainImage" :alt="food.name" class="main-image">
          
          <!-- 评分功能移到图片下面 -->
          <div class="review-section">
            <h3>给商品评分</h3>
            <div class="review-form">
              <el-rate v-model="newReview.rating" size="large" />
              <el-button type="primary" size="large" @click="submitReview" :disabled="!canSubmitReview">
                提交评分
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="food-info">
          <h1>{{ food.foodName }}</h1>
          <div class="rating-section">
            <el-rate 
              :model-value="parseFloat(food.foodRating) || 0" 
              disabled 
              show-text 
              allow-half
              :texts="['非常差', '差', '一般', '好', '非常好']"
            />
            <span class="review-count">({{ food.totalReviews || 0 }} 评分)</span>
          </div>
          <p class="price">¥{{ food.foodPrice }}</p>
          <p class="description">{{ food.foodDescription }}</p>
          
          <div class="restaurant-info">
            <h3>餐厅信息</h3>
            <div class="restaurant-card" @click="goToRestaurant">
              <img :src="'/businessmen.png'" :alt="food.merchantName" class="restaurant-logo">
              <div class="restaurant-details">
                <h4>{{ food.merchantName }}</h4>
                <p>{{ food.merchantAddress || '地址信息待完善' }}</p>
                <p>{{ food.contactPhone || '联系电话待完善' }}</p>
              </div>
            </div>
          </div>
          

        </div>
      </div>
      
      <div class="reviews-section">
        <div class="review-statistics">
          <div class="rating-overview">
            <div class="average-rating">
              <span class="rating-number">{{ food.foodRating || 0 }}</span>
              <el-rate :model-value="parseFloat(food.foodRating) || 0" disabled allow-half />
              <span class="total-reviews">共 {{ food.totalReviews || 0 }} 条评分</span>
            </div>
            <div class="rating-distribution">
              <div v-for="star in 5" :key="star" class="rating-bar">
                <span>{{ 6 - star }}星</span>
                <div class="bar-container">
                  <div class="bar-fill" :style="{ width: getRatingPercentage(6 - star) + '%' }"></div>
                </div>
                <span class="bar-count">{{ getRatingCount(6 - star) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="review-list">
          <div v-if="loading" class="loading-text">正在加载评价...</div>
          <div v-else v-for="review in reviews" :key="review.ratingId" class="review-item">
            <div class="review-header">
              <div class="user-info">
                <img src="/businessmen.png" :alt="review.username" class="user-avatar">
                <span class="username">{{ review.username }}</span>
              </div>
              <div class="review-meta">
                <el-rate :model-value="parseFloat(review.rating) || 0" disabled size="small" allow-half />
                <span class="review-date">{{ formatDate(review.ratingTime) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
  name: 'FoodDetailView',
  data() {
    return {
      loading: true,
      newReview: {
        rating: 0
      },
      food: {},
      reviews: [],
      ratingDistribution: {}
    }
  },
  async created() {
    await this.loadFoodDetail()
    await this.loadFoodReviews()
  },
  computed: {
    // 当前主图
    currentMainImage() {
      return this.food.foodImagePath || '/food.png'
    },
    canSubmitReview() {
      return this.newReview.rating > 0
    }
  },
  methods: {
    // 加载菜品详情
    async loadFoodDetail() {
      try {
        const foodId = this.$route.params.id
        const response = await fetch(`http://localhost:2077/api/food/${foodId}`)
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.food = data.data
          } else {
            this.$message.error('获取菜品详情失败')
          }
        } else {
          this.$message.error('获取菜品详情失败')
        }
      } catch (error) {
        console.error('加载菜品详情失败:', error)
        this.$message.error('网络错误，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    
    // 加载菜品评价
    async loadFoodReviews() {
      try {
        const foodId = this.$route.params.id
        const response = await fetch(`http://localhost:2077/api/food/${foodId}/reviews`)
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.reviews = data.data.reviews || []
            this.ratingDistribution = data.data.distribution || {}
          }
        }
      } catch (error) {
        console.error(error)
      }
    },
    goToRestaurant() {
      this.$router.push(`/merchant/${this.food.merchantId}`)
    },
    
    async submitReview() {
      if (!this.canSubmitReview) {
        this.$message.warning('请先给商品评分')
        return
      }
      
      try {
        const token = localStorage.getItem('token')
        if (!token) {
          this.$message.error('请先登录')
          this.$router.push('/login')
          return
        }
        
        const response = await fetch('http://localhost:2077/api/reviews', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            foodId: this.food.foodId,
            merchantId: this.food.merchantId,
            rating: this.newReview.rating
          })
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.success) {
            this.$message.success('评分提交成功！')
            this.newReview.rating = 0
            // 重新加载评价数据
            await this.loadFoodReviews()
            await this.loadFoodDetail() // 重新加载以更新评分
          } else {
            // 简化错误信息显示
            let errorMsg = data.message || '提交失败'
            if (errorMsg.includes('您已经评价过该菜品')) {
              errorMsg = '您已经评价过该菜品'
            }
            this.$message.error(errorMsg)
          }
        } else {
          this.$message.error('提交失败')
        }
      } catch (error) {
        console.error('提交评分失败:', error)
        this.$message.error('网络错误，请稍后重试')
      }
    },
    getRatingPercentage(star) {
      const total = Object.values(this.ratingDistribution).reduce((sum, count) => sum + count, 0)
      const count = this.ratingDistribution[star.toString()] || 0
      return total > 0 ? (count / total) * 100 : 0
    },
    getRatingCount(star) {
      return this.ratingDistribution[star.toString()] || 0
    },
    formatDate(dateTime) {
      if (!dateTime) return '未知时间'
      return new Date(dateTime).toLocaleDateString('zh-CN')
    }
  }
}
</script>

<style scoped>
.food-detail-view {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 容器样式 */

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.food-detail-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.food-images {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.main-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}



.food-info h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 15px;
}

.rating-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.review-count {
  color: #666;
  font-size: 14px;
}

.price {
  font-size: 28px;
  font-weight: bold;
  color: #e74c3c;
  margin-bottom: 20px;
}

.description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 30px;
  font-size: 16px;
}

.restaurant-info h3 {
  color: #333;
  margin-bottom: 15px;
}

.restaurant-card {
  display: flex;
  gap: 15px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 30px;
}

.restaurant-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.restaurant-logo {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.restaurant-details h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.restaurant-details p {
  margin: 2px 0;
  color: #666;
  font-size: 14px;
}

.review-section {
  border-top: 1px solid #eee;
  padding-top: 30px;
}

.review-section h3 {
  color: #333;
  margin-bottom: 20px;
}

.review-form {
  display: flex;
  align-items: center;
  gap: 20px;
}

.reviews-section {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.reviews-section h2 {
  color: #333;
  margin-bottom: 25px;
}

.review-statistics {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.rating-overview {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 30px;
}

.average-rating {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.rating-number {
  font-size: 48px;
  font-weight: bold;
  color: #409eff;
}

.total-reviews {
  color: #666;
  font-size: 14px;
}

.rating-distribution {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.rating-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.rating-bar span:first-child {
  width: 30px;
  color: #666;
}

.bar-container {
  flex: 1;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  background: #409eff;
  transition: width 0.3s;
}

.bar-count {
  width: 30px;
  text-align: right;
  color: #666;
}

.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.loading-text, .no-reviews {
  text-align: center;
  padding: 40px;
  color: #666;
  font-size: 16px;
}

.review-item {
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.username {
  font-weight: bold;
  color: #333;
}

.review-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.review-date {
  color: #999;
  font-size: 12px;
}

@media (max-width: 768px) {
  .nav-menu {
    display: none;
  }
  
  .food-detail-card {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 20px;
  }
  
  .rating-overview {
    grid-template-columns: 1fr;
    gap: 20px;
  }
}
</style> 